import json

from fastapi import Request, APIRouter, Body
from datetime import datetime, timedelta
from core.Auth import decode_access_token
from core.Response import success, fail
from core.Utils import process_payment_request, random_str
from models.models import Post, PostDteta, Comment, User_vip, Userposts, User, Tag
from schemas.posts import detail_id, serialize_posts, Post_Pydantic, Comment_Pydantic, CommentCreateRequest

router = APIRouter(prefix='')


@router.post('/')
async def yh_detail(request: Request, detail_id: detail_id = Body(...)):
    recent_posts_queryset = await Post.get(id=detail_id.id).prefetch_related("post_detail")
    if recent_posts_queryset is None:
        return fail(msg={"detail": "Post not found"})

    recent_posts_queryset.views += 1
    await recent_posts_queryset.save()

    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    post_detail = recent_posts_queryset.post_detail
    response_data = {
        "id": recent_posts_queryset.id,
        "imageSrc": post_detail.imageSrc[:3],
        "text": recent_posts_queryset.text,
        "title": recent_posts_queryset.title,
        "likes": recent_posts_queryset.likes,
        "comments_count": recent_posts_queryset.comments_count,
        "views": recent_posts_queryset.views,
        "publishDate": recent_posts_queryset.publishDate,
        "collection": post_detail.Collection

    }

    if decoded_data is None:
        return success(data=response_data)

    user_id = decoded_data.get('id')
    user=await User.get(id=user_id)
    user_vip = await User_vip.get_or_none(user=user)

    if user_vip and user_vip.vip_status:
        response_data["imageSrc"] = post_detail.imageSrc
        return success(data=response_data)

    user_posrs = await Userposts.get_or_none(posts=detail_id.id, user=user_id)
    if user_posrs and user_posrs.is_order:
        if user_posrs.code:
            current_time = datetime.now()
            last_integral_time = user_posrs.time
            last_integral_time=datetime.strptime(last_integral_time, "%Y-%m-%d %H:%M:%S.%f")
            print(current_time, last_integral_time)
            # 将 user.integral_time 转换为 datetime 对象

            # 判断是否过了一天
            if current_time - last_integral_time >= timedelta(days=1):
                user_posrs.code = None
                await user_posrs.save()

                return success(data=response_data)
        response_data["imageSrc"] = post_detail.imageSrc
        return success(data=response_data)

    return success(data=response_data)


@router.get("/comment/{post_id}", )
async def get_comments(post_id: int):
    comments = await Comment.filter(post_id=post_id)
    serializer = [await Comment_Pydantic.from_tortoise_orm(comment) for comment in comments]

    response_data = {
        "data": serializer,
    }
    return success(data=serializer)


@router.post("/comment", )
async def create_comment(request: Request, comment_data: CommentCreateRequest = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    user_id = decoded_data.get('id')
    comment_data_dict = comment_data.dict()
    comment_data_dict['user_id'] = user_id

    comment = await Comment.create(**comment_data_dict)
    serializer = await Comment_Pydantic.from_tortoise_orm(comment)

    response_data = {
        "code": 0,
        "msg": "Comment created successfully",
        "data": serializer,
    }

    return success(data=response_data)


@router.post('/orderimg')
async def integral(request: Request, detail_id: detail_id = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误,请检查是否已登录！')
    user = await User.get(id=decoded_data['id'])
    user_posrs = await Userposts.get_or_none(posts=detail_id.id, user=user, is_order=1)
    if user_posrs:
        return fail(msg='您已购买过该商品')
    print(user, 'user', detail_id.id)
    if user is None:
        return fail(msg='用户信息错误')

    recent_posts_queryset = await Post.get(id=detail_id.id)
    first_tag = await recent_posts_queryset.tags.first()
    print(first_tag)  # 打印第一个 tag，如果有的话
    menoy = await Tag.get(id=first_tag.id).values('price')
    pid=f'https://ylxue.top/detail/{detail_id.id}'

    order = await process_payment_request(recent_posts_queryset.title, menoy.get('price'), user.client_host, pid=pid)
    # print(order)
    redis_order={
        "user": user.id,
        "posts": recent_posts_queryset.id,
        "order_link": order['order_no'],

    }
    await request.app.state.cache.set(order['order_no'], json.dumps(redis_order, default=str),ex=300)
    return success(data=order)


@router.post('/share')
async def integral(request: Request, detail_id: detail_id = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误,请检查是否已登录！')
    print(decoded_data, 'decoded_data')
    user = await User.get_or_none(id=decoded_data['id'])
    print(user, 'user', detail_id.id)
    if user is None:
        return fail(msg='用户信息错误')
    if user.is_share_code:
        code = user.share_code
        return success(data=code)
    user.is_share_code = 1
    code = random_str()
    user.share_code = code
    await user.save()
    last_four_chars = code[-5:]
    print(last_four_chars)
    await request.app.state.cache.set(last_four_chars, json.dumps(code, default=str))

    # 获取 Post 对象
    post = await Post.get(id=detail_id.id)
    await Userposts.create(user=user, posts=post, code=code, time=datetime.now())
    return success(data=code)